﻿using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace Program08
{
    class Program
    {
        /// <summary>
        /// 利用序列化存储对象到文件流中
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            var p = new Person()
            {
                Name = "哦哦哦",
                No = "00001",
                Age = 19
            };
            //把对象存放在文件中
            using (FileStream fsWrite = new FileStream("person.db", FileMode.OpenOrCreate, FileAccess.Write))
            {
                //读对象内容,转换为二进制,序列化
                var buffer = new BinaryFormatter();
                buffer.Serialize(fsWrite,p);
            }
            Console.WriteLine("序列化成功,存储成功！");

            //从文件中读出对象的内容
            //Person p;
            using (FileStream fsRead=new FileStream("person.db",FileMode.OpenOrCreate,FileAccess.Read))
            {
                var buffer = new BinaryFormatter();
                p =(Person) buffer.Deserialize(fsRead);

            }
            Console.Write("工号{0} 姓名{1} 年龄{2}",p.No ,p.Name,p.Age);
        
        }
    }
    //定义可序列化的类
    [Serializable]
    public class Person
    {
        //姓名
        public string Name { get; set; }
        //年龄
        public int Age { get; set; }
        //工号
        public string No { get; set; }
    }
}
